<template>
  <div :class="['echarts-box', hasBorder ? '' : 'no-border']">
    <article :style="{'text-align':textAlign}">{{title}}</article>
    <div class="echarts-dom" :id="`echart-dom${rendomNum}`"></div>
  </div>
</template>
<script lang="ts" setup>
//@ts-ignore
import { TextAlignProperty } from 'csstype';
import { ref, getCurrentInstance, onMounted, onUnmounted, nextTick,  } from 'vue';
const { proxy } = getCurrentInstance() as any 
const props = withDefaults(defineProps<{option: any, title: string, hasBorder?: boolean, textAlign?: TextAlignProperty, mode?: string}>(), {
  option: () => {},
  title: '',
  hasBorder: true,
  textAlign: 'left',
  mode: 'normal' // normal => 通过组件内mounted周期调用, hook => 通过父组件 hook:mounted 方式调用
})
// 随机数取整
const rendomNum = ref<number>(Math.random() * 1000 | 0)
// 这里我在csdn上解释很清楚
// https://blog.csdn.net/qq_39404437/article/details/121009610?spm=1001.2014.3001.5501
let echartRef: any = null

const echartResize = () => {
  echartRef.resize()
}
const chartsInit = () => {
  nextTick(() => {
    let echartDom = document.querySelector(`#echart-dom${rendomNum.value}`)
    echartRef = proxy.$echarts.init(echartDom)
    props.option && echartRef.setOption(props.option)
  })
}
// 曝光自身的方法， 供父组件调用
defineExpose({
  echartResize,
  chartsInit
})
onMounted(() => {
  if (props.mode === 'normal') {
    let echartDom = document.querySelector(`#echart-dom${rendomNum.value}`)
    echartRef = proxy.$echarts.init(echartDom)
    props.option && echartRef.setOption(props.option)
  }
})
onUnmounted(() => {
  echartRef && echartRef.dispose()
})
</script>
<style lang="scss" scoped>
.echarts-box {
  width: 100%;
  height: 100%;
  padding: 0 20px 19px;
  border: 1px solid #14637D;
  position: relative;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 16px;
    // background: url('../../assets/images/board-header.png') no-repeat;
    background-size: 100% 100%;
  }
  article {
    font-size: 16px;
    font-weight: 400;
    color: #FFFFFF;
    line-height: 43px;
  }
  .echarts-dom {
    width: 100%;
    height: calc(100% - 62px);
  }
}
.no-border {
  border: none;
}
</style>
